#define  _CRT_SECURE_NO_WARNINGS 1
#include "list.h"

ListNode* ListNodeCreate(x)
{
	ListNode* pn = (ListNode*)malloc(sizeof(ListNode));
	pn->data = x;
	pn->next = NULL;
	pn->prev = NULL;
	return pn;
}

ListNode* ListNodeInit()
{
	ListNode* phead = ListNodeCreate(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListNodePrint(ListNode* phead)
{
	ListNode* curr = phead->next;
	while (curr != phead)
	{
		printf(LTDataPrintType, curr->data);
		curr = curr->next;
	}
	printf("\n");
}

void ListNodePushBack(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* tail = phead->prev;
	ListNode* newnode = ListNodeCreate(x);

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void ListNodePushFront(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* first = phead->next;
	ListNode* newnode = ListNodeCreate(x);

	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = first;
	first->prev = newnode;

}

void ListNodePopFront(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	ListNode* first = phead->next;
	ListNode* second = first->next;

	phead->next = second;
	second->prev = phead;

	free(first);
	first = NULL;
}

void ListNodePopBack(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	ListNode* tail = phead->prev;
	ListNode* prev = tail->prev;

	prev->next = phead;
	phead->prev = prev;

	free(tail);
	tail = NULL;
}

ListNode* ListNodeFind(ListNode* phead, LTDataType x)
{
	ListNode* curr= phead->next;
	while (curr != phead)
	{
		if (curr->data == x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}

void ListNodeInsert(ListNode* phead, ListNode* pos, LTDataType x)
{
	assert(pos);

	ListNode* newnode = ListNodeCreate(x);
	ListNode* prev = pos->prev;

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode; 
}
void ListNodeErase(ListNode* phead, ListNode* pos)
{
	assert(pos);
	assert(pos != phead);

	ListNode* prev = pos->prev;
	ListNode* next = pos->next;

	prev->next = next;
	next->prev = prev;

	free(pos);
	pos = NULL;
}

void ListNodeDestory(ListNode* phead)
{
	ListNode* curr = phead->next;
	while (curr != phead)
	{
		ListNode* next = curr->next;
		free(curr);
		curr = next;
	}
	free(phead);
	phead = NULL;
}
